<template>
    <div class="container">
      <el-dialog :title="setTitle" :visible.sync="dialogVisible" @close='closeDialog' :close-on-click-modal='false'>
        <el-form :model="dataForm" ref="dataForm" :rules="dataRule" label-width="120px" size="mini" class="common-dialog-height" v-loading="formLoading">
          <el-form-item label="登录帐号：" prop="userName">
            <el-input v-model="dataForm.userName" placeholder="请输入登录帐号" :disabled="dialogType!=='add'"></el-input>
          </el-form-item>
          <el-form-item label="用户名称：" prop="userAlias">
            <el-input v-model="dataForm.userAlias" placeholder="请输入用户名" :disabled="inputDisabled"></el-input>
          </el-form-item>
          <el-form-item label="登录密码：" prop="userPassword" v-if="inputSeen">
            <el-input v-model="dataForm.userPassword" type="password" placeholder="请输入密码" :disabled="inputDisabled"></el-input>
          </el-form-item>
          <el-form-item label="确认密码：" prop="passwordAgain" v-if="inputSeen">
            <el-input v-model="dataForm.passwordAgain" type="password" placeholder="请再次输入密码" :disabled="inputDisabled"></el-input>
          </el-form-item>
          <el-form-item label="性别：" prop="userSex">
            <el-radio-group v-model="dataForm.userSex">
              <el-radio :label="0" :disabled="inputDisabled">女</el-radio>
              <el-radio :label="1" :disabled="inputDisabled">男</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号码：" prop="userPhone">
            <el-input v-model="dataForm.userPhone" placeholder="请输入手机号码" :disabled="inputDisabled"></el-input>
          </el-form-item>
          <el-form-item label="邮箱地址：" prop="userEmail">
            <el-input v-model="dataForm.userEmail" placeholder="请输入邮箱地址" :disabled="inputDisabled"></el-input>
          </el-form-item>
          <el-form-item label="角色信息：" v-if="dialogType === 'detail'">
            <el-input v-model="roleInfo" disabled></el-input>
          </el-form-item>
          <el-form-item label="描述：" prop="userDesc">
            <el-input v-model="dataForm.userDesc" type="textarea" :rows="3" placeholder="请输入用户描述" maxlength="100" show-word-limit :disabled="inputDisabled"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">关 闭</el-button>
          <el-button v-if="dialogType!=='detail'" type="primary" @click="formDataSubmit()">提 交</el-button>
        </span>
      </el-dialog>
    </div>
</template>
<script>
  import { checkPassword, isEmail, isMobile } from '@/utils/validator'
  export default {
    data () {
      var validatePassword = (rule, value, callback) => {
        if (this.dialogType === 'add' && !checkPassword(value)) {
          callback(new Error('密码长度为6~16位的数字或英文字母!'))
        } else {
          callback()
        }
      }
      var validatePasswordAgain = (rule, value, callback) => {
        if (this.dialogType === 'add' && this.dataForm.userPassword !== value) {
          callback(new Error('确认密码与密码输入不一致!'))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('手机号码格式不正确!'))
        } else {
          callback()
        }
      }
      var validateEmail = (rule, value, callback) => {
        if (value !== '' && !isEmail(value)) {
          callback(new Error('邮箱格式不正确!'))
        } else {
          callback()
        }
      }
      return {
        formLoading: false,
        dialogType: '',
        dialogVisible: false,
        dataForm: {
          userId: '',
          userName: '',
          userAlias: '',
          userPassword: '',
          passwordAgain: '',
          userSex: 0,
          userPhone: '',
          userEmail: '',
          userDesc: ''
        },
        roleInfo: '',
        dataRule:{
          userName: [
            { required: true, message: '请输入登录帐号!', trigger: 'blur' },
            { min: 5, max: 20, message: '账号长度为5~20个字符!', trigger: 'blur' }
          ],
          userAlias: [
            { required: true, message: '请输入用户名!', trigger: 'blur' },
            { min: 2, max: 10, message: '用户名长度为2~10个字符!', trigger: 'blur' }
          ],
          userPassword: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          passwordAgain: [
            { validator: validatePasswordAgain, trigger: 'blur' }
          ],
          userPhone: [
            { required: true, validator: validateMobile, trigger: 'blur' }
          ],
          userEmail: [
            { validator: validateEmail, trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
      setTitle() {
        const type = this.dialogType
        if (type === 'add') {
          return '新增用户'
        } else if (type === 'edit') {
          return '编辑用户'
        } else if (type === 'detail') {
          return '查看用户详情'
        }
      },
      inputDisabled() {
        return this.dialogType === 'detail'
      },
      inputSeen() {
        return this.dialogType === 'add'
      }
    },
    methods: {
      init(params) {
        this.dialogVisible = true
        this.dialogType = params.type
        if (params.type === 'edit' || params.type === 'detail') {
          this.formLoading = true
          this.$http.get(this.$http.adornUrl(`/sys/user/info/${params.id}`)).then(response => {
            const result = response.data
            if (result && result.code === 200) {
              const data = result.data
              this.dataForm.userId = data.userId
              this.dataForm.userName = data.userName
              this.dataForm.userAlias = data.userAlias
              this.dataForm.userSex = data.userSex
              this.dataForm.userPhone = data.userPhone
              this.dataForm.userEmail = data.userEmail
              this.dataForm.userDesc = data.userDesc
              this.roleInfo= (data.roleNames.length > 0) ? data.roleNames.join(',') : ''
            } else {
              this.$message({message: result.msg, type: 'error'})
            }
            this.formLoading = false
          }).catch(reason => {
            this.$message({message: reason, type: 'error'})
            this.formLoading = false
          })
        }
      },
      formDataSubmit(){
        if (this.dialogType === 'add' || this.dialogType === 'edit'){
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              const tips = this.dialogType === 'add' ? '新增' : '修改'
              const url = this.dialogType === 'add' ? this.$http.adornUrl('/sys/user/info') : this.$http.adornUrl(`/sys/user/info/${this.dataForm.userId}`) ;
              const method = this.dialogType === 'add' ? 'post' : 'put'
              this.$http({
                url: url,
                method: method,
                data: this.$http.adornData(this.dataForm)
              }).then(response => {
                const result = response.data
                if (result && result.code === 200) {
                  this.$emit('refreshData')
                  this.dialogVisible = false
                  this.$message({message: tips + result.msg, type: 'success'})
                } else {
                  this.$message({message: tips + result.msg, type: 'error'})
                }
              }).catch(reason => {
                this.$message({message: reason, type: 'error'})
              })
            }
          })
        }
      },
      closeDialog(){
        this.$refs['dataForm'].resetFields()
        this.dialogType = ''
        this.roleInfo = ''
      }
    }
  }
</script>
<style>
</style>
